package com.softao.ming.gde.internal.core.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import com.softao.ming.gde.core.model.IBundleManifestFile;
import com.softao.ming.gde.core.model.IBundleVersion;

/**
 * 
 */
public class BundleManifestFileImpl implements IBundleManifestFile {
	/** */
	public static final String KEY_SOURCE_BUNDLE = "Eclipse-SourceBundle";
	
	/** */
	public static final String KEY_SYMBOLIC_NAME = "Bundle-SymbolicName";
	
	/** */
	public static final String KEY_BUNDLE_VERSION = "Bundle-Version";
	
	private final Map<String, String> mProperties;
	
	/**
	 * @param inputStream input stream to the MANIFEST.MF file
	 * @throws IOException 
	 */
	public BundleManifestFileImpl(InputStream inputStream) throws IOException {
		mProperties = new HashMap<String, String>();
		
		InputStreamReader isr = new InputStreamReader(inputStream);
		BufferedReader reader = new BufferedReader(isr);
		
		String line = reader.readLine();
		while (line != null) {
			line = line.trim();
			
			if (line.length() > 0 || !line.startsWith("#")) {
				int index = line.indexOf(":");
				if (index > 0) {
					String key = line.substring(0, index).trim();
					String value = line.substring(index + 1).trim();
					mProperties.put(key, value);
				}
			}
			
			line = reader.readLine();
		}
	}
	
	/**
	 * @return <code>true</code> if this bundle is individual source bundle.
	 */
	public final boolean isSourceBundle() {
		return mProperties.containsKey(KEY_SOURCE_BUNDLE);
	}
	
	/**
	 * @param key
	 * @return <code>true</code> the key exists; otherwise, <code>false</code>.
	 */
	public final boolean contains(String key) {
		return mProperties.containsKey(key);
	}
	
	/**
	 * @return the unique identifier of the bundle
	 */
	public final String getBundleUniqueIdentifier() {
		String symbolicName = mProperties.get(KEY_SYMBOLIC_NAME);
		String[] parts = symbolicName.split(";");
		return parts[0].trim();
	}

	@Override
	public IBundleVersion getBundleVersion() {
		return new BundleVersionImpl(mProperties.get(KEY_BUNDLE_VERSION));
	}
	
	@Override
	public String get(String key) {
		return mProperties.get(key);
	}
}
